import tool from './tool'
import store from './store'
import printTaskHandler from '../modules/printTaskHandler'

export default () => {
  // 响应服务器WS状态检查请求
  tool.webSocket.onMessage('update', () => {
    tool.webSocket.sendMessage('updateReceived')
  })
  
  // WS断连时自动重连
  tool.webSocket.onClosed(async () => {
    if (store.getItem('doNotReConnectWS')) {
      store.removeItem('doNotReConnectWS')
      return
    }
    await tool.wait(0.5)
    tool.webSocket.connect()
    let t = setInterval(() => {
      if (tool.webSocket.isConnected) return
      tool.webSocket.connect()
    }, 2000);
    tool.webSocket.onConnected(() => {
      clearInterval(t)
    })
  })

  // WS显示消息，通常用于测试
  tool.webSocket.onMessage('showMessage', (e) => {
    tool.handleShowModel(e, false)
  })

  // WS新订单通知
  tool.webSocket.onMessage('newOrder', async (e) => {
    // 如果开启了自动打印按钮，就开始打印订单
    if (wx.getStorageSync('autoPrint') == 'true') {
      // tool.handleShowModel(e.orderNo)
      console.log('打印', e.orderNo)
      tool.printLabel(e.orderNo)
    }

  })
}